<script setup>
import { Modal } from 'ant-design-vue'
import { ColumnHeightOutlined, DownOutlined, PlusOutlined, ReloadOutlined, SettingOutlined, UpOutlined } from '@ant-design/icons-vue'
import { getUserDetail, getUserLst, resetFreeze, resetPass, resetUnfreeze, updateUser } from '~@/api/user/index'

defineOptions({
  name: 'USER',
})
const formRef = ref()
const labelCol = {
  span: 6,
}
const wrapperCol = {
  span: 14,
}
const formState = reactive({
  userId: '',
  userName: '',
  gender: '',
  email: '',
  phone: '',
  address: '',
  certNo: '',
})
const rules = {
  userName: [
    { required: true, message: '必填字段', trigger: 'change' },
  ],
  phone: [
    { required: true, message: '必填字段', trigger: 'change' },
  ],
}

const statusMap = {
  0: '关闭',
  1: '运行中',
  2: '上线',
  3: '错误',
}
const message = useMessage()
const columns = shallowRef([
  {
    title: '姓名',
    dataIndex: 'userName',
    width: 150,
  },
  // {
  //   title: '卡号',
  //   dataIndex: 'cardNo',
  //   width: 200,
  // },

  {
    title: '手机号',
    dataIndex: 'phone',
    width: 150,
  },
  {
    title: '证件号',
    dataIndex: 'certNo',
    width: 200,
  },
  {
    title: '年龄',
    dataIndex: 'gender',
    width: 100,
    customRender: ({ text }) => {
      if (text) {
        return text
      }
      else {
        return '-'
      }
    },
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    width: 180,
    customRender: ({ text }) => {
      if (text) {
        return text
      }
      else {
        return '-'
      }
    },
  },

  {
    title: '地址',
    dataIndex: 'address',
    ellipsis: true,
    width: 150, // 限制宽度
    customRender: ({ text }) => {
      if (text) {
        return text
      }
      else {
        return '-'
      }
    },
  },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: 180,

  },
])
const detailInfo = shallowRef({
  userName: void 0,
  gender: void 0,
  phone: void 0,
  certNo: void 0,
  email: void 0,
  address: void 0,

})
const tradeOptions = shallowRef([
  // { label: '支付', value: 'DEFRAY' },
  // { label: '退费', value: 'REFUND' },
  // { label: '充值', value: 'RECHARGE' },
  // { label: '提现', value: 'WITHDRAWAL' },
])
const statusOptions = shallowRef([
  { configKey: 'ACTIVE', configValue: '正常' },
  { configKey: 'AUTO_FREEZE', configValue: '自动冻结' },
  { configKey: 'MANUAL_FREEZE', configValue: '人工冻结' },
  { configKey: 'CANCEL', configValue: '注销' },
])
const loading = shallowRef(false)
const totalNum = shallowRef(0)
const pagination = reactive({
  pageSize: 8,
  pageSizeOptions: ['10', '20', '30', '40'],
  current: 1,
  total: totalNum,
  showSizeChanger: true,
  // showQuickJumper: true,
  showTotal: total => `总共：${total}`,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    init()
  },
})
const dataSource = shallowRef([])
const formModel = reactive({
  name: void 0,
  callNo: void 0,
  desc: void 0,
  status: void 0,
  updatedAt: void 0,
})
const tableSize = ref(['large'])
const open = ref(false)
const editOpen = ref(false)
const options = computed(() => {
  return columns.value.map((item) => {
    if (item.dataIndex === 'action') {
      return {
        label: item.title,
        value: item.dataIndex,
        disabled: true,
      }
    }
    return {
      label: item.title,
      value: item.dataIndex,
    }
  })
})
const dropdownVisible = ref(false)
const getCheckList = computed(() => columns.value.map(item => item.dataIndex))
const state = reactive({
  indeterminate: false,
  checkAll: true,
  checkList: getCheckList.value,
})
onMounted(() => {
  init()
  // getType();
  // getChannel();
})
// 搜索
async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    const createBeginTime = formModel.cardDate?.[0]?.format('YYYY-MM-DD')
    const createEndTime = formModel.cardDate?.[1]?.format('YYYY-MM-DD')
    const { data } = await getUserLst({
      param: { ...formModel, createBeginTime, createEndTime },
      page: {
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
      },

    })

    dataSource.value = data.data ?? []
    // dataSource.value = data.data ?? []
    totalNum.value = data.pageInfo.total
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}
// 更新用户信息
async function onSubmit() {
  try {
    await formRef.value.validate()
    const params = {
      userId: formState.userId,
      userName: formState.userName,
      phone: formState.phone,
      email: formState.email,
      address: formState.address,

    }
    const { data } = await updateUser(params)
    message.success('保存成功')
    init()
    open.value = false
  }
  catch (error) {
    // message.error('请检查表单填写是否正确')
  }
}
function resetForm() {
  formRef.value.resetFields()
}
// 返回
function handleReturn() {
  editOpen.value = false
}
async function onSearch() {
  pagination.current = 1
  await init()
}
// 重置查询参数
async function onReset() {
  formModel.userName = void 0
  formModel.phone = void 0
  await init()
}

// 编辑
async function handleEdit(record) {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  open.value = true
  formState.userId = record.userId
  formState.userName = record.userName
  formState.gender = record.gender
  formState.email = record.email
  formState.address = record.address
  formState.certNo = record.certNo
  formState.phone = record.phone
}

function handleSizeChange(e) {
  tableSize.value[0] = e.key
}
function filterAction(value) {
  return columns.value.filter((item) => {
    if (value.includes(item.dataIndex))
      return true

    return false
  })
}
const filterColumns = ref(filterAction(getCheckList.value))
function handleCheckAllChange(e) {
  Object.assign(state, {
    checkList: e.target.checked ? getCheckList.value : [],
    indeterminate: true,
  })
  filterColumns.value = e.target.checked ? filterAction(getCheckList.value) : filterColumns.value.filter(item => item.dataIndex === 'action')
}
watch(
  () => state.checkList,
  (val) => {
    state.indeterminate = !!val.length && val.length < getCheckList.value.length
    state.checkAll = val.length === getCheckList.value.length
  },
)
// 处理证件号
function handleCertcard(certNo) {
  if (!certNo)
    return ''
  const len = certNo.length
  if (len <= 4)
    return certNo // 短于4位不处理
  return certNo.slice(0, 3) + '*'.repeat(len - 7) + certNo.slice(-4)
}
function handleResetChange() {
  state.checkList = getCheckList.value
  filterColumns.value = filterAction(getCheckList.value)
}
function handleCheckChange(value) {
  const filterValue = filterAction(value)
  filterColumns.value = filterValue
}
const expand = ref(false)
</script>

<template>
  <page-container>
    <a-card mb-4>
      <a-form :model="formModel" layout="inline">
        <a-form-item name="userName" label="用户姓名" style="margin-bottom:20px;">
          <a-input v-model:value="formModel.userName" placeholder="模糊查询" allow-clear />
        </a-form-item>
        <a-form-item name="phone" label="手机号" style="margin-bottom:20px;">
          <a-input v-model:value="formModel.phone" placeholder="精确查询" allow-clear />
        </a-form-item>
        <a-form-item name="phone">
          <a-space flex justify-end w-full>
            <!-- :loading="loading" -->
            <a-button type="primary" @click="onSearch">
              查询
            </a-button>
            <a-button @click="onReset">
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <a-card>
      <a-table bordered :loading="loading" :columns="filterColumns" :scroll="{ x: 1000 }" :data-source="dataSource" :pagination="pagination">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'defrayFee'">
            <span :style="{ color: record.defrayFee < 0 ? 'red' : 'black' }">{{ Number(record.defrayFee).toFixed(2) }}</span>
          </template>
          <!-- <template v-else-if="column.dataIndex === 'certNo'">
              {{ handleCertcard(record.certNo) }}
            </template> -->
          <template v-else-if="column.dataIndex === 'action'">
            <div class="resetPass flex flex-center">
              <a @click="handleEdit(record)">编辑</a>
              <a v-if="record.status === 'ACTIVE'" @click="handleFreeze(record)">冻结账户</a>
              <a v-if="record.status === 'MANUAL_FREEZE'" @click="handleUnfreeze(record)">解冻账户</a>
            </div>
          </template>
        </template>
      </a-table>
    </a-card>

    <a-modal v-model:open="open" :centered="true" title="编辑用户" width="800px" @ok="onSubmit">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        class="mt-12 mb-12"
      >
        <a-form-item label="姓名" name="userName">
          <a-input v-model:value="formState.userName" />
        </a-form-item>
        <a-form-item label="手机号" name="phone">
          <a-input v-model:value="formState.phone" placeholder="请输入手机号" />
        </a-form-item>
        <a-form-item label="身份证号" name="certNo">
          <a-input v-model:value="formState.certNo" disabled />
        </a-form-item>
        <a-form-item label="年龄" name="gender">
          <a-input v-model:value="formState.gender" disabled />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="formState.email" placeholder="请输入邮箱" />
        </a-form-item>
        <a-form-item label="地址" name="address">
          <a-textarea v-model:value="formState.address" placeholder="请输入地址" :rows="2" />
        </a-form-item>
      </a-form>
    </a-modal>
  </page-container>
</template>

    <style lang="less" scoped>
      .resetPass{
        a{
          margin-right: 10px;
        }
      }
      .red{
        color:red;
        /* color:#ff4d4f; */
      }
      .card-title{
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        flex: auto;
        color: rgba(0, 0, 0, 0.88);
        font-weight: 600;
        font-size: 16px;
        line-height: 1.5;
      }
    @media screen and (max-width: 1200px) and (min-width: 992px) {
      .activeCard {
        margin-bottom: 24px;
      }
      .members {
        margin-bottom: 0;
      }
      .extraContent {
        margin-left: -44px;
        .statItem {
          padding: 0 16px;
        }
      }
    }

    @media screen and (max-width: 992px) {
      .activeCard {
        margin-bottom: 24px;
      }
      .members {
        margin-bottom: 0;
      }
      .extraContent {
        float: none;
        margin-right: 0;
        .statItem {
          padding: 0 16px;
          text-align: left;
          &::after {
            display: none;
          }
        }
      }
    }

    @media screen and (max-width: 768px) {
      .extraContent {
        margin-left: -16px;
      }
      .projectList {
        .projectGrid {
          width: 50%;
        }
      }
    }

    @media screen and (max-width: 576px) {
      .pageHeaderContent {
        display: block;
        .content {
          margin-left: 0;
        }
      }
      .extraContent {
        .statItem {
          float: none;
        }
      }
    }

    @media screen and (max-width: 480px) {
      .projectList {
        .projectGrid {
          width: 100%;
        }
      }
    }
    </style>
